package com.by.common.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.UUID;
import java.util.concurrent.ConcurrentNavigableMap;
import java.util.concurrent.ConcurrentSkipListMap;

/**
 * @author ServivE
 * @version 0.1
 * @className RabbitUtils
 * @description
 * @date 2024/10/24 17:29
 * @since jdk17
 */
@Component
@Slf4j //日志的注解 通过log记录日志信息
public class RabbitUtils {
    ConcurrentSkipListMap sendMap = new ConcurrentSkipListMap();//存储发送的消息

    @Autowired
    RabbitTemplate rabbitTemplate;

    /**
     * 异步确认发送消息
     *
     * @param msg
     */
    public void send(String msg) {
        //设置监听
        rabbitTemplate.setConfirmCallback((correlationData, ack, cause) -> {
            if (ack) {
                //消息投递成功
                log.info("消息[" + sendMap.get(correlationData.getId()) + "]投递成功");
            } else {
                //消息投递失败
                log.info("消息[" + sendMap.get(correlationData.getId()) + "]投递失败" + cause);
            }
        });
        //发送数据
        String id = UUID.randomUUID().toString();
        //将id与消息关联
        sendMap.put(id, msg);
        rabbitTemplate.send("", "orderQueue", new Message(msg.getBytes()), new CorrelationData(id));
    }
    /**
     * 延迟发送
     *
     * @param msg
     * @param lazyTime 延迟时间单位 ms
     */
    public void sendLazy(String msg, int lazyTime) {
        MessageProperties mp = new MessageProperties();
        mp.setHeader("x-delay", lazyTime);
        Message message = new Message(msg.getBytes(), mp);
        rabbitTemplate.send("lazyEx", "lazy", message);
    }

}
